<template>
  <div class="layout-wrapper" :class="{debug}">
      <LeftPanel />
      <div class="layout-painter">
        <SmoothDndContainer class="block-group" 
          orientation="vertical"
          tag="div"  group-name="blocks" 
          @drop="(payload)=>{
            console.log('payload',payload);
            const newBlocks=applyDrag(blocks,payload)
            editorStore.updateBlocks(newBlocks)
          }"  
          >
            <SmoothDndDraggable v-for="block in blocks" :key="block.id">
              <!-- <div class="block-item">{{block}}</div> -->
               <div 
                  :class="{'block-wrapper':true,debug:debug||activeBlockId===block.id}" 
                  :data-block-type="block.type" 
                  :data-block-id="block.id"
                  @click="()=>editorStore.selectBlock(block)"
                  >
                <BlockRenderer :block="block" />
               </div>
            </SmoothDndDraggable>
          </SmoothDndContainer>
      </div>
      <div>
        <RightPanel />
      </div>
</div>
</template>

<script lang="ts" setup>
// import AppLeftPanel from '@/components/AppLeftPanel/AppLeftPanel';
import { storeToRefs } from 'pinia';
import type { DropResult } from 'smooth-dnd';

import BlockRenderer from '@/blocks/BlockRenderer.vue';
import LeftPanel from '@/components/LeftPanel.vue';
import RightPanel from '@/components/RightPanel/RightPanel.vue';
import {SmoothDndContainer} from '@/components/SmoothDnd/SmoothDndContainer'
import {SmoothDndDraggable} from '@/components/SmoothDnd/SmoothDndDraggable'
import {useDebugStore} from '@/stores/debug'
import {useEditorStore} from '@/stores/editor'
import {arrayMove} from '@/utils/array';


const debugStore = useDebugStore()
const editorStore = useEditorStore()

const {debug}=storeToRefs(debugStore)
const {blocks,activeBlockId}=storeToRefs(editorStore)

const applyDrag=<T extends any[]>(arr:T,dragResult:DropResult)=>{
  const {addedIndex,removedIndex,payload}=dragResult

  const result = [...arr]

  if(addedIndex===null) return result;

  // 添加：从外面拖进来是添加
  if(addedIndex!==null&&removedIndex===null){
    result.splice(addedIndex,0,payload)
  }

  // 移动：内部拖拽是移动
  if(addedIndex!==null&&removedIndex!==null){
    return arrayMove(result,removedIndex,addedIndex)
  }
  return result
}

</script>
<style>
.layout-wrapper {
  display: flex;
  flex-direction: row;
  height: 100%;
}
.layout-painter{
  width:100%;
  overflow-y: auto;
  padding: 20px;
}
.block-wrapper{
  padding: 20px;
  margin: 20px 0;
  border-radius:4px;
  border:2px dashed transparent;
}
.block-wrapper.debug{
  /* border:2px dashed #e8e8e8; */
  border-color: #00a4ff;
}
</style>
